package br.pucrs.prototipoonline.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

import br.pucrs.prototipoonline.util.DatabaseUtil;
import br.pucrs.prototipoonline.vo.ElementoVO;


/**
 * 
 * @author Ricardo Luckei
 * @author Gelson Gentil
 *
 */
public class ElementosDAO extends BaseDAO {

	public ElementosDAO() {
	}
	
	public void criarElemento(ElementoVO elemento) throws SQLException {
		StringBuffer sql = new StringBuffer();
		sql.append("insert into elementos (tela_id, dados) values(?,?) ");
		
		Connection con = DatabaseUtil.getConnection();
		
		try {
			PreparedStatement ps = con.prepareStatement(sql.toString());
			ps.setInt(1, elemento.getTelaId().intValue());
			ps.setString(2, elemento.getDados());
			
			ps.execute();
		} finally {
			con.close();
		}
	}
	
	public void removerElementosTela(Integer telaId) throws SQLException {
		StringBuffer sql = new StringBuffer();
		sql.append("delete from elementos where tela_id=?");
		
		Connection con = DatabaseUtil.getConnection();
		
		try {
			PreparedStatement ps = con.prepareStatement(sql.toString());
			ps.setInt(1, telaId);
			
			ps.execute();
		} finally {
			con.close();
		}
	}

	public void atualizarElemento(ElementoVO elemento) throws SQLException {
		StringBuffer sql = new StringBuffer();
		sql.append("update elementos set dados=? where id=? and tela_id=?");
		
		Connection con = DatabaseUtil.getConnection();
		
		try {
			PreparedStatement ps = con.prepareStatement(sql.toString());
			ps.setString(1, elemento.getDados());
			ps.setInt(2, elemento.getId().intValue());
			ps.setInt(3, elemento.getTelaId().intValue());
			
			ps.execute();
		} finally {
			con.close();
		}
	}

	public Collection<ElementoVO> buscarElementos(ElementoVO elemento) throws SQLException {
		StringBuffer sql = new StringBuffer();
		sql.append("select id, tela_id, dados from elementos where tela_id=?");
		
		Connection con = DatabaseUtil.getConnection();
		
		try {
			PreparedStatement ps = con.prepareStatement(sql.toString());
			ps.setInt(1, elemento.getTelaId().intValue());
			
			ResultSet rs = ps.executeQuery();
			return populateCollection(rs, ElementoVO.class);
		} finally {
			con.close();
		}
	}

}
